'use strict';

const { Controller } = require('egg');

class UserController extends Controller {
	async index() {
		const { ctx } = this;
		ctx.body = '访问了登录路由';
	}

	//验证码路由
	async code() {
		const { ctx } = this;
		console.log('后端接收的验证码', this.ctx.request.body);
		// clink = this.ctx.body;
		let mycode = Math.floor(Math.random() * 1000000)
			.toString()
			.padStart(6, 0);

		if (1 == 1) {
			//为了注册能拿到验证码 存在客户端上
			ctx.session.code = mycode;
			setTimeout(() => {
				ctx.session.code = null;
			}, 5 * 60 * 1000);
			ctx.body = {
				mycode: mycode,
				code: 1,
				data: '验证码发送成功',
			};
		} else {
			ctx.body = {
				code: -1,
				data: '验证码发送失败',
			};
		}
		// ctx.body = { code: mycode };
	}

	//注册路由接口
	async register() {
		const { ctx } = this;
		let clientData = ctx.request.body;
		console.log(clientData);
		//判断验证码是否正确
		if (clientData.code == ctx.session.code) {
			//操作数据库
			const results = await this.app.mysql.select('user', {
				// 搜索 user 表
				where: { tel: clientData.tel }, // WHERE 条件
			});
			//注册路由的register
			// console.log(clientData.tel);
			// console.log(clientData.password);
			console.log(results, '查找出来的数据');
			console.log(results.length, '查找出来的数据长度');

			if (results.length == 0) {
				//如果没有数据就把账号添加进入数据库
				const result = await this.app.mysql.insert('user', {
					tel: clientData.tel,
					pwd: clientData.password,
					nickname: clientData.nickname,
					gender: clientData.gender,
				});

				// 注册成功就登录
				// ctx.session.uid = result.insertId;
				ctx.body = {
					code: 1,
					// uid: result.insertId,
					data: '注册成功',
				};
			} else {
				//长度不为0证明tel已经存在
				ctx.body = {
					code: -1,
					data: '该账号已经注册过了 ',
				};
			}
		} else {
			ctx.body = {
				code: -3,
				data: '验证码错误',
			};
		}
	}
}

module.exports = UserController;
